const Jimp = require('jimp');

const imagePath = '1.jpeg';
const outputImagePath = '3.jpg';

const watermarkWidth = 250;
const watermarkHeight = 80;

Jimp.read(imagePath)
    .then(image => {
        const imageWidth = image.bitmap.width;
        const imageHeight = image.bitmap.height;

        // 计算水印的位置（右下角）
        const watermarkX = imageWidth - watermarkWidth;
        const watermarkY = imageHeight - watermarkHeight;

        // 获取水印区域上方和左侧的颜色平均值
        const aboveColor = getAverageColor(image, watermarkX, watermarkY - 1, watermarkWidth, 1); // 上方一行的颜色
        const leftColor = getAverageColor(image, watermarkX - 1, watermarkY, 1, watermarkHeight); // 左侧一列的颜色

        // 将水印区域的颜色替换为上方和左侧颜色的平均值
        const averageColor = {
            r: Math.round((aboveColor.r + leftColor.r) / 2),
            g: Math.round((aboveColor.g + leftColor.g) / 2),
            b: Math.round((aboveColor.b + leftColor.b) / 2),
        };

        image.scan(watermarkX, watermarkY, watermarkWidth, watermarkHeight, function (x, y, idx) {
            this.bitmap.data[idx] = averageColor.r;
            this.bitmap.data[idx + 1] = averageColor.g;
            this.bitmap.data[idx + 2] = averageColor.b;
        });

        // 保存处理后的图片
        return image.write(outputImagePath);
    })
    .catch(err => {
        console.error(err);
    });

// 获取区域颜色的平均值
function getAverageColor(image, x, y, width, height) {
    let totalR = 0;
    let totalG = 0;
    let totalB = 0;
    let pixelCount = 0;

    image.scan(x, y, width, height, function (i, j, idx) {
        totalR += this.bitmap.data[idx];
        totalG += this.bitmap.data[idx + 1];
        totalB += this.bitmap.data[idx + 2];
        pixelCount++;
    });

    const averageR = Math.round(totalR / pixelCount);
    const averageG = Math.round(totalG / pixelCount);
    const averageB = Math.round(totalB / pixelCount);

    return { r: averageR, g: averageG, b: averageB };
}
